from asyncio.runners import run
from ..tools.spider.const import HOT_DICT
from . import api
import asyncio
from app import redis_client, executor, cache
from flask import json, jsonify, request, abort

EMAIL_PREFIX = 'pytools:user:email'

# 并发获取首页数据
async def hot_info(keyword: str):
    result = redis_client.get(f'pytools:info:{keyword}')
    # print(datetime.datetime.now())
    if result is None:
        return ''
    return {keyword: json.loads(result.decode('utf-8'))}


# 获取首页数据
async def get_index():
    # 生成所有的任务
    task = [hot_info(keyword=keyword) for keyword in HOT_DICT.keys()]
    # 并发执行任务
    info = await asyncio.gather(*task)
    return info

# 添加邮箱到redis
def add_email(data: str):
    redis_client.lpush(EMAIL_PREFIX, data)
    redis_client.persist(EMAIL_PREFIX)


# 请求首页数据, 使用缓存策略
@api.route('/info/index', methods=['GET'])
@cache.cached(timeout=60*60, key_prefix='index')
def index():
    result = asyncio.run(get_index())
    processed = dict()
    if '' in result:
        abort(404)
    for item in result:
        if 'zhihu' in item.keys():
            processed['zhihu'] = item.get('zhihu')
        elif 'weibo' in item.keys():
            processed['weibo'] = item.get('weibo')
        elif 'douyin' in item.keys():
            processed['douyin'] = item.get('douyin')
    
    return jsonify(data=processed)

# 订阅邮箱
@api.route('/info/subscribe', methods=['POST'])
def subscribe():
    data = request.json
    data = json.dumps(data)
    # 异步优化
    if data:
        executor.submit(add_email, data)
    return jsonify(msg='订阅成功')


